# frozen_string_literal: true

module QA
  module EE
    module Resource
      class VulnerabilityItem < QA::Resource::Base
        attributes :id, :severity
        attribute :name do
          SecureRandom.base64(6)
        end
        attribute :description do
          SecureRandom.base64(24)
        end
        attribute :scanner_name do
          SecureRandom.hex(6)
        end
        attribute :mutation_id do
          SecureRandom.hex(6)
        end
        attribute :scanner_id do
          "gid://gitlab/Vulnerabilities::Scanner/#{rand(10000)}"
        end

        # GraphQl endpoint to create a vulnerability
        #
        # @return [String]
        def api_post_path
          "/graphql"
        end

        def resource_web_url(resource)
          super
        rescue ResourceURLMissingError
          # this particular resource does not expose a web_url property
        end

        # Defining api_get_path because it is required to be overridden for an api resource class
        #
        # @return [String]
        def api_get_path
          "/graphql"
        end

        # Graphql mutation for vulnerability item creation
        #
        # @return [String]
        def api_post_body
          <<~GQL
            mutation {
                vulnerabilityCreate(input:{
                            project: "gid://gitlab/Project/#{id}",
                            clientMutationId: "#{mutation_id}",
                            name: "#{name}",
                            description: "#{description}",
                            scanner:{
                              name: "#{scanner_name}",
                              id: "#{scanner_id}",
                              url: "http://localhost/jk",
                              version: "1.1"
                            },
                            identifiers: {
                              name: "CVE-#{SecureRandom.hex(6)}",
                              url: "http://localhost"
                            },
                            severity: #{severity}
                            }
                            )
                            {
                              errors
                              clientMutationId
                              vulnerability: vulnerability {
                                id
                                vulnerabilityPath
                                project {
                                  id
                                  fullPath
                                }
                              }
                            }
                          }
          GQL
        end
      end
    end
  end
end
